package com.yx.cloud.activity;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.iot.base.service.req.CancelAccountParam;
import com.iot.base.service.req.GetAuthCodeParam;
import com.iot.base.service.resp.GetVerifyCodeResponse;
import com.iot.sweeper.AppContext;
import com.yx.cloud.R;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.databinding.ContinuelogoutActivityBinding;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.RegularCheckUtils;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.ToastUtil;
import com.iot.common.utils.Event;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class ContinueLogoutActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "ContinueLogoutActivity";

    private String userAccount, type, mContryCode;
    private ContinuelogoutActivityBinding binding;
    private TimeCount time;
    private TimeCountCode timeCode;

    @Override
    public void onCreate() {
        binding = ContinuelogoutActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
        initData();
    }

    private void initData() {
        type = getIntent().getStringExtra("type");
        userAccount = getIntent().getStringExtra("userAccount");
        mContryCode = getIntent().getStringExtra("contryCode");
        binding.etCancelAccountPhonenum.setText(userAccount);
        binding.etCancelAccountPhonenum.setEnabled(false);

//        if ("phoneNumer".equals(type)) {
//            binding.tvCancelAccountType.setText(getString(R.string.phone));
//        } else {
//            binding.tvCancelAccountType.setText(getString(R.string.email));
//        }
//        Log.i(TAG, cancel_ccount + " initData  contryCode  2222: " + mContryCode);
//        if (RegularCheckUtils.isMobile(cancel_ccount)) {
//            binding.tvCancelAccountAccount.setText(mContryCode + "-" + cancel_ccount);
//        } else {
//            binding.tvCancelAccountAccount.setText(cancel_ccount);
//        }
        binding.btnConfirmLogout.setEnabled(false);
        /**
         * 对帐号密码输入框进行监听
         */
        binding.etCancelAccountPhonenum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

                if (!"".equals(editable.toString().trim()) &&
                        binding.etVerificationCode.length() >= 4 &&
                        binding.etCancelAccountPassWord.length() >= 6) {
                    binding.btnConfirmLogout.setEnabled(true);
                } else {
                    binding.btnConfirmLogout.setEnabled(false);
                }
            }
        });
        binding.etVerificationCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

                if (!"".equals(editable.toString().trim()) &&
                        binding.etCancelAccountPhonenum.length() >= 6 &&
                        binding.etCancelAccountPassWord.length() >= 6) {
                    binding.btnConfirmLogout.setEnabled(true);
                } else {
                    binding.btnConfirmLogout.setEnabled(false);
                }
            }
        });
        binding.etCancelAccountPassWord.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

                if (!"".equals(editable.toString().trim()) &&
                        binding.etCancelAccountPhonenum.length() >= 6 &&
                        binding.etVerificationCode.length() >= 4) {
                    binding.btnConfirmLogout.setEnabled(true);
                } else {
                    binding.btnConfirmLogout.setEnabled(false);
                }
            }
        });

        binding.ivCancelAccountReturn.setOnClickListener(this);
        binding.tvCancelAccountGetVerificationCode.setOnClickListener(this);
        binding.btnConfirmLogout.setOnClickListener(this);
        binding.tbCancelAccountPassword.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        int id = v.getId();
        if (id == R.id.tb_password_hide) {
            binding.etCancelAccountPhonenum.setText("");
        } else if (id == R.id.tb_cancelAccountPassword) {
            if (binding.tbCancelAccountPassword.isChecked()) {
                binding.etCancelAccountPassWord.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                binding.etCancelAccountPassWord.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            }
            binding.etCancelAccountPassWord.setSelection(binding.etCancelAccountPassWord.getText().toString().trim().length());
        } else if (id == R.id.iv_Cancel_Account_Return) {
            Intent_utils.backIntent(this);
        } else if (id == R.id.tv_cancelAccountGetVerificationCode) {
            Log.d(TAG, "    IIIIIIIII-a-ccccccccccccccccccccccccc---" + mContryCode);
            String phoneNum = binding.etCancelAccountPhonenum.getText().toString().trim();
            //获取验证码
            if (phoneNum.equals("")) {
                ToastUtil.show(ContinueLogoutActivity.this, "account is empty ", Toast.LENGTH_SHORT);
                return;
            }
            if (timeCode == null) {
                //获取验证码计时
                timeCode = new TimeCountCode(60000, 1000);
                timeCode.start();
            }
            GetAuthCodeParam param = new GetAuthCodeParam();
            String mCountryCode = binding.tvCancelAccountGetVerificationCode.getText().toString().trim();
            param.setAccount(phoneNum);
            param.setCountryCode(mCountryCode);
            param.setType(GetAuthCodeParam.TYPE_CANCLE);
            AppContext.getAccountService().getAuthCode(param);

        } else if (id == R.id.btn_confirmLogout) {
            String phoneNum = binding.etCancelAccountPhonenum.getText().toString().trim();
            String passWord = binding.etCancelAccountPassWord.getText().toString().trim();
            String code = binding.etVerificationCode.getText().toString().trim();
            if (passWord.isEmpty()) {
                Toast.makeText(this, getString(R.string.U_T_Pw_Null), Toast.LENGTH_LONG).show();
                return;
            }
            if (code.isEmpty()) {
                Toast.makeText(this, getString(R.string.U_T_Code_No), Toast.LENGTH_LONG).show();
                return;
            }
            if (RegularCheckUtils.isMobile(phoneNum)) {
                type = "phone";
            } else {
                if (RegularCheckUtils.isEmail(phoneNum)) {
                    type = "emall";
                } else {
                    Toast.makeText(this, getString(R.string.U_T_Un_NoFormat), Toast.LENGTH_LONG).show();
                    return;
                }
            }
            AppContext.getAccountService().cancelAccount(CancelAccountParam.newBuilder().account(phoneNum).authCode(code).password(passWord).build());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_GET_AUTH_CODE:
                //注销验证码获取成功
                if (event.isResult()) {
                    //成功不处理
                } else {
                    GetVerifyCodeResponse response = (GetVerifyCodeResponse) event.getContent();
                    if (response.getErrorCode() == GetVerifyCodeResponse.ERROR_REGISTER_CODE_USER_EXIST) {
                        //注册验证码的用户存在
                        ToastUtil.showShort(this, getString(R.string.L_T_Register_Un_Existed));
                    } else if (response.getErrorCode() == GetVerifyCodeResponse.ERROR_CHANGE_PASSWORD_USER_NOT_EXIST) {
                        //修改密码验证码的用户不存在
                        ToastUtil.showShort(this, getString(R.string.U_T_Un_No));
                    } else if (response.getErrorCode() == GetVerifyCodeResponse.ERROR_REQUEST_COUNT_LIMIT) {
                        //验证码请求次数限制
                        ToastUtil.showShort(this, getString(R.string.U_T_Code_TimesLimit));
                    } else if (response.getErrorCode() == GetVerifyCodeResponse.ERROR_REQUEST_FREQUENCY_LIMIT) {
                        //验证码请求太过频繁 一分钟三次
                        ToastUtil.showShort(this, getString(R.string.U_T_Code_Frequently));
                    } else if (response.getErrorCode() == GetVerifyCodeResponse.ERROR_INVALID_ACCOUNT_FORMAT) {
                        //账号格式错误
                        ToastUtil.showShort(this, getString(R.string.U_T_Un_NoFormat));
                    }else if (response.getErrorCode() == GetVerifyCodeResponse.ERROR_NETWORK) {
                        ToastUtil.showShort(this, getString(R.string.U_T_Network_Err));
                    } else if (response.getErrorCode() == GetVerifyCodeResponse.ERROR_SERVER) {
                        ToastUtil.showShort(this, getString(R.string.U_T_Server_Err));
                    } else {
                        ToastUtil.showShort(this, getString(R.string.U_UnknownErr));
                    }
                }
                break;
            case Event.MESSAGE_TYPE_CANCEL_ACCOUNT:
                Log.d(TAG, "    vvvvvvvv- xxxxx 注销 注销---");
                if (event.isResult()) {
                    binding.llAccountHasBeenCancelled.setVisibility(View.VISIBLE);
                    if (time == null) {
                        //获取验证码计时
                        time = new TimeCount(2000, 1000);
                        time.start();
                    }
                } else {
                    ToastUtil.show(this, "注销失败", Toast.LENGTH_SHORT);
                }
                break;
        }
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            Intent intent = new Intent(ContinueLogoutActivity.this, LoginActivity.class);
            startActivity(intent);
            time = null;
        }
    }

    class TimeCountCode extends CountDownTimer {

        public TimeCountCode(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            binding.tvCancelAccountGetVerificationCode.setClickable(false);
            binding.tvCancelAccountGetVerificationCode.setText(getResources().getString(R.string.U_AgainGet_Btn) + "(" + millisUntilFinished / 1000 + ")");
        }

        @Override
        public void onFinish() {
            binding.tvCancelAccountGetVerificationCode.setText(getResources().getString(R.string.U_GetCode_Btn));
            binding.tvCancelAccountGetVerificationCode.setClickable(true);
            timeCode = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (time != null) {
            time = null;
        }
        if (timeCode != null) {
            timeCode = null;
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
